package com.example.bishetianqi;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.example.bishetianqi.base.BaseActivity;
import com.example.bishetianqi.db.DBManager;
import com.example.bishetianqi.unti.Httputil;
import com.squareup.picasso.Picasso;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.prefs.Preferences;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class MainActivity extends BaseActivity implements View.OnClickListener{

    private LocationClient mlocationClient;
    SharedPreferences.Editor editor;
    ImageView add_city,bizhiImg;
    LinearLayout pointlayout;
    TextView nowtime;
   // String TAG="lzw";
    ViewPager view_city;
    String gpscity;
    List<Fragment>fragmentList;//ViewPaper的数据源
    List<String>cityList;//需要显示城市的集合
    List<ImageView>imgList;//页数指数的集合
    private CityFragmentPagerAdapter cityFragmentPagerAdapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //状态栏和软件融合，把状态栏颜色设置为透明
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }

        setContentView(R.layout.activity_main);
        initLocationcity();
        initview();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM月dd日 HH:mm");// HH:mm:ss
        //获取当前时间
        Date date = new Date(System.currentTimeMillis());
        nowtime.setText("更新时间："+simpleDateFormat.format(date));
        fragmentList=new ArrayList<>();
        cityList= DBManager.queryAllCity(); //获取数据库中的城市信息列表
        //cityList=new ArrayList<>();
        imgList=new ArrayList<>();

        SharedPreferences preferences1= PreferenceManager.getDefaultSharedPreferences(this);
        String bizhi=preferences1.getString("bing_pic",null);
        if (bizhi!=null){
            Picasso.with(getApplicationContext()).load(bizhi).into(bizhiImg);
        }
        gpscity=preferences1.getString("locationcity","");

//        SharedPreferences preferences=getSharedPreferences("gpscity",MODE_PRIVATE);
//        String gpscity=preferences.getString("locationcity","");

        if (cityList.size()==0) {
            cityList.add(gpscity);
        }

        if(cityList.contains(gpscity)){
            cityList.remove(gpscity);
        }
//        cityList.remove(gpscity);
        cityList.add(gpscity);

        /* 因为可能搜索界面点击跳转此界面，会传值，所以此处获取一下*/
        try {
            Intent intent = getIntent();
            String city = intent.getStringExtra("city");
            if (!cityList.contains(city)&&!TextUtils.isEmpty(city)) {
                cityList.add(city);
            }
        }catch (Exception e){
            Log.i("lzw","程序出现问题了！");
        }

        //初始化Viewpaper的方法
        initViewpaper();
        cityFragmentPagerAdapter = new CityFragmentPagerAdapter(getSupportFragmentManager(),fragmentList);
        view_city.setAdapter(cityFragmentPagerAdapter);

        //初始化页面指示器
        initpoint();

        //设置显示的城市界面
        view_city.setCurrentItem(0);

        //设置Viewpaper的监听器
        setpaperListener();

    }


    /*监听的方法*/
    private void setpaperListener() {
        view_city.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                    for (int i=0;i<imgList.size();i++){
                        imgList.get(i).setImageResource(R.drawable.a1);
                    }
                    imgList.get(position).setImageResource(R.drawable.a2);
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });


    }

    private void initpoint() {
        for (int i=0;i<fragmentList.size();i++){
            ImageView pointImg=new ImageView(this);
            pointImg.setImageResource(R.drawable.a1);
            pointImg.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,LinearLayout.LayoutParams.WRAP_CONTENT));
            LinearLayout.LayoutParams lp= (LinearLayout.LayoutParams) pointImg.getLayoutParams();
            lp.setMargins(0,0,15,0);
            imgList.add(pointImg);
            pointlayout.addView(pointImg);
        }
        imgList.get(0).setImageResource(R.drawable.a2);
    }

    private void initViewpaper() {
        /*创建Fragment对象，添加到数据源FragmentList*/
        for(int i=0;i<cityList.size();i++){
            CityWeatherFragment cityWeatherFragment=new CityWeatherFragment();
            Bundle bundle=new Bundle();
            bundle.putString("city",cityList.get(i));
            cityWeatherFragment.setArguments(bundle);
            fragmentList.add(cityWeatherFragment);
        }
    }

    private void initview() {
        add_city=findViewById(R.id.add_city);
        add_city.setOnClickListener(this);
        nowtime=findViewById(R.id.nowtime);
        bizhiImg=findViewById(R.id.bizhi);
        pointlayout=findViewById(R.id.layout_point);
        view_city=findViewById(R.id.view_city);
    }

    private void initLocationcity() {
        mlocationClient=new LocationClient(getApplicationContext());
        mlocationClient.registerLocationListener(new MyLocationListener());
        List<String> permissionList=new ArrayList<>();
        if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.READ_PHONE_STATE)!=PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.READ_PHONE_STATE);
        }
        if (ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE)!=PackageManager.PERMISSION_GRANTED){
            permissionList.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (!permissionList.isEmpty()){
            String[] permission=permissionList.toArray(new String[permissionList.size()]);
            ActivityCompat.requestPermissions(MainActivity.this,permission,1);
        }else{
            requestLocation();
        }
    }

    private void requestLocation() {
        initLocation();
        mlocationClient.start();
    }

    private void initLocation() {
        LocationClientOption option=new LocationClientOption();
        option.setScanSpan(5000);
        option.setIsNeedAddress(true);
        option.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        mlocationClient.setLocOption(option);
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        //获取数据库中的城市的集合
        List<String> cityList1 = DBManager.queryAllCity();
        if (cityList1.size()==0){
            cityList1.add(gpscity);
        }
        cityList.clear();//重写加载之前，清空原本数据源
        cityList.addAll(cityList1);
        //剩余的城市也要创建Fragment
        fragmentList.clear();;
        initViewpaper();
        cityFragmentPagerAdapter.notifyDataSetChanged();
        //小圆点的个数也要变化
        imgList.clear();
        pointlayout.removeAllViews();
        initpoint();
        view_city.setCurrentItem(0);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mlocationClient.stop();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode){
            case 1:
                if(grantResults.length>0){
                    for(int result:grantResults){
                        if (result!=PackageManager.PERMISSION_GRANTED){
                            Toast.makeText(this, "需获取所有权限", Toast.LENGTH_SHORT).show();
                            finish();
                            return;
                        }
                    }
                    requestLocation();
                }else {
                    Toast.makeText(this, "发生位置错误", Toast.LENGTH_SHORT).show();
                    finish();
                }
                break;
            default:
                break;

        }
    }

    public class MyLocationListener  implements BDLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            String test=bdLocation.getCity();
            String[] strings=test.split("市");
            String locationcity=strings[0];
//            cityList.add(locationcity);
//            long i=DBManager.addcityInfo(locationcity,null);
//            Log.d("123", "onReceiveLocation: "+Integer.toString((int) i));
//            SharedPreferences sharedPreferences= getApplicationContext().getSharedPreferences("gpscity", Activity.MODE_PRIVATE);
//            SharedPreferences.Editor editor=sharedPreferences.edit();
//            editor.putString("locationcity",locationcity);
//            editor.commit();
              editor=PreferenceManager.getDefaultSharedPreferences(getApplication()).edit();
              editor.putString("locationcity",locationcity);
              editor.apply();

        }
    }


    @Override
    public void onClick(View v) {
        Intent intent=new Intent();
        switch (v.getId()){
            case R.id.add_city:
                intent.setClass(this,CityManagerActivity.class);
                break;
        }
        startActivity(intent);
    }

}





